/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package eu.fastl.dragster.web.filter;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import javax.servlet.ServletOutputStream;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

/**
 * Servlet Response Wrapper which caches the Response Output
 *
 * @author Ernst Fastl
 */
public class CachingServletResponseWrapper extends HttpServletResponseWrapper {

    private final CachingServletOutputStream outputStream;

    private PrintWriter writer;

    public CachingServletResponseWrapper(ServletResponse response) throws IOException {
    	super((HttpServletResponse)response);
        this.outputStream = new CachingServletOutputStream(response.getOutputStream());
    }

    @Override
    public ServletOutputStream getOutputStream() throws IOException {
       return this.outputStream;
    }

    @Override
    public PrintWriter getWriter() throws IOException {
        if(this.writer == null){
            if(getCharacterEncoding() == null){
                this.writer = new PrintWriter(this.outputStream);
            } else {
                this.writer = new PrintWriter(new OutputStreamWriter(this.outputStream, getCharacterEncoding()));
            }
        }
        return this.writer;
    }

    @Override
    public void reset() {
        super.reset();
        this.outputStream.reset();
    }

    @Override
    public void resetBuffer() {
        super.resetBuffer();
        this.outputStream.reset();
    }


}
